package com.david.func_test.view

import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.widget.FrameLayout
import androidx.core.view.updateLayoutParams
import kotlin.math.abs

class PagerViewGroup(context: Context, attr: AttributeSet?) : FrameLayout(context, attr) {
    private var itemWidth = 0
    private var currentIndex = 0
    private lateinit var moreText: MoreTextView

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        itemWidth = measuredWidth - 100
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        val count = childCount

        for (i in 0 until count - 1) {
            val child = getChildAt(i)
            if (child.visibility != GONE) {
                (child).layout(i * itemWidth, 0, (i + 1) * itemWidth,  height)
            }
        }
        moreText = getChildAt(count - 1) as MoreTextView
        moreText.layout((count - 1) * itemWidth, 0,
            ((count - 1) * itemWidth + 100 - distance).toInt(),  height)
    }

    private var touchDownX: Float = 0f
    private var touchDownY: Float = 0f

    private var onTouch = false

    private var distance = 0f

//    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
//        when(ev?.action) {
//            MotionEvent.ACTION_DOWN -> {
////                touchDownX = ev.x
////                touchDownY = ev.y
//
////                super.dispatchTouchEvent(ev)
//                return true
//            }
//
//            MotionEvent.ACTION_MOVE -> {
//                Log.e("move", "dispatchTouchEvent move: ${(ev.x - touchDownX).toString()}")
////                onTouch = abs(ev.x - touchDownX) > abs(ev.y - touchDownY)
////                if (onTouch) {
////                parent.requestDisallowInterceptTouchEvent(true);
//
//                return true
////                }
//            }
//        }
//        return super.dispatchTouchEvent(ev)
//    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        when(ev?.action) {
            MotionEvent.ACTION_DOWN -> {
                touchDownX = ev.x
                touchDownY = ev.y

                lastTouchTime = System.currentTimeMillis()
//                super.onInterceptTouchEvent(ev)
                return true
            }

            MotionEvent.ACTION_MOVE -> {
                Log.e("move", "dispatchTouchEvent move: ${(ev.x - touchDownX).toString()}")
                if (!onTouch) {
                    onTouch = abs(ev.x - touchDownX) > abs(ev.y - touchDownY)
                }
//                if (onTouch) {
                    return true
//                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                return true
            }
        }
        return true
//        return super.onInterceptTouchEvent(ev)
    }

    private var lastX = 0

    private var lastPositionX = 0

    private var lastTouchTime = 0L

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        when(ev?.action) {
            MotionEvent.ACTION_DOWN -> {
                return true
            }

            MotionEvent.ACTION_MOVE -> {
                if (!onTouch)
                    onTouch = abs(ev.x - touchDownX) > 5 && abs(ev.x - touchDownX) > abs(ev.y - touchDownY)

                if (onTouch) {
                    parent.requestDisallowInterceptTouchEvent(true);

                    Log.e("move", "onTouchEvent move: ${(ev.x - touchDownX).toString()}")
                    distance = ev.x - touchDownX

                    lastPositionX = -(ev.x - touchDownX).toInt() + lastX
                    scrollTo(lastPositionX, 0)

                    if (currentIndex == 3 && distance < 0) {
                        moreText.updateLayoutParams<LayoutParams> { width = (100 - distance).toInt() }
                    }
                }
                return true
            }
            MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                if (onTouch) {
                    val distance = (ev.x - touchDownX).toInt()
                    //负数为向左滑动，正数为向右滑动
                    Log.e("move", "onTouchEvent ACTION_UP: $distance")


                    if (distance > 150 && currentIndex > 0) {
//                        自动滑动到上一项
                        --currentIndex
                        lastX = currentIndex * itemWidth
//                        scrollTo(-currentIndex * itemWidth, 0)
                        startAnim(lastPositionX, lastX)
                    } else if (distance < -150) {
                        if (currentIndex == 3) {//滑动到了最后一项
                            startAnim(lastPositionX, lastX)
                        } else {
//                        自动滑动到下一项
                            ++currentIndex
                            lastX = currentIndex * itemWidth
                            startAnim(lastPositionX, lastX)
                        }
//                        scrollTo(-currentIndex * itemWidth, 0)
                    } else {
//                        滑动到当前位置
                        startAnim(lastPositionX, lastX)
//                        scrollTo(lastX, 0)
                    }
                    lastPositionX = lastX

//                    记录上次滑动的位置
//                    lastX -= distance
                    onTouch = false
                    return true
                } else if (System.currentTimeMillis() - lastTouchTime < 100 && ev.x < itemWidth) {
                    Log.e("move", "click: ${System.currentTimeMillis() - lastTouchTime}")
                }
            }
        }
//        return super.onTouchEvent(ev)
        return true
    }

    private var animStartX = 0

    private fun startAnim(start: Int, end: Int) {
        if (start > end && currentIndex == 3) {
            if (moreText.getExpend()) {
                // TODO: 显示了释放查看文字
            }
        }
        animStartX = start
        val animator = ValueAnimator.ofInt(start, end)
        animator.duration = (300).toLong()
        animator.addUpdateListener { anim ->
            scrollTo(anim.animatedValue as Int, 0)
            if (start > end && currentIndex == 3) {
                distance = (end - (anim.animatedValue as Int).toFloat())
                moreText.updateLayoutParams<LayoutParams> { width = (100 - distance).toInt() }
            }
        }

        animator.start()
    }
}